package net.e_agri.wap;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.e_agri.action.Authentication;
import net.e_agri.cache.AgriCacheManager;
import net.e_agri.cache.ContentCacheManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesServiceFactory;

@SuppressWarnings("serial")
public class PostTopicServlet extends HttpServlet {
	
	private static final Log log = LogFactory.getLog(PostTopicServlet.class);

	private static String uriRoot = "";
	
	private static String selfRoot = "";

	private BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();

	private static ContentCacheManager cacheManager = null;

	public void init(){
		uriRoot = getServletContext().getInitParameter("UriRoot");
		selfRoot = getServletContext().getInitParameter("SelfRoot");
		cacheManager = new AgriCacheManager();
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	  throws ServletException, IOException {

		
	}
	
	@SuppressWarnings("unchecked")
	private void processTopic(HttpServletRequest req, Authentication auth){

		StringBuffer logBuf = new StringBuffer();
		for(String paramName : (Set<String>)req.getParameterMap().keySet())
			logBuf.append("\n\t").append(paramName).append(" = [")
				.append(req.getParameter(paramName)).append("]");
		log.info(logBuf.toString());

	  	Map<String, String> targetId_to_ActionMap = new HashMap<String, String>();
	  		targetId_to_ActionMap.put("target_c_commu_topic_comment_id", "do_c_bbs_delete_c_commu_topic_comment");
	  		targetId_to_ActionMap.put("target_c_commu_topic_id", "do_c_bbs_delete_c_commu_topic");
	  		targetId_to_ActionMap.put("target_c_diary_comment_id", "do_fh_diary_delete_c_diary_comment");
		Map<String, String> targetId_to_cacheAction = new HashMap<String, String>();
			targetId_to_cacheAction.put("target_c_commu_topic_comment_id", "page_c_topic_detail");
			targetId_to_cacheAction.put("target_c_commu_topic_id", "page_c_topic_list");
			targetId_to_cacheAction.put("target_c_diary_comment_id", "page_fh_diary");
		Map<String, String> targetId_to_parentId = new HashMap<String, String>();
			targetId_to_parentId.put("target_c_commu_topic_comment_id", "target_c_commu_topic_id");
			targetId_to_parentId.put("target_c_commu_topic_id", "target_c_commu_id");
			targetId_to_parentId.put("target_c_diary_comment_id", "target_c_diary_id");
		
		List<String> arrayTypeKeyList = new ArrayList<String>();
		arrayTypeKeyList.add("target_c_diary_comment_id");

		//String topicUrl = req.getParameter("topic_id");
		String cacheUrl = "";
		Map<String, String> param = new LinkedHashMap<String, String>();

	  	param.put("m", "pc");
	  	if(auth != null)
	  		param.put("sessid", auth.getSessid());
	  	
	  	Map<String, String> parentParam = new LinkedHashMap<String, String>();
	  	String[] token = null;
	  	if(req.getParameter("parent_id") != null)
	  		for(String tk : req.getParameter("parent_id").split(" ")) {
	  			token = tk.split("=");
	  			if(token[0].startsWith("&") || token[0].startsWith("?"))
	  				parentParam.put(token[0].substring(1), token[1]);
	  			else
	  				parentParam.put(token[0], token[1]);
	  		}
	  	log.info("parent_id -> " + parentParam.toString());

  		for(String targetKey : targetId_to_ActionMap.keySet()){
	  		if(req.getParameter(targetKey) != null){

		  		param.put("a", targetId_to_ActionMap.get(targetKey));
		  		
		  		if(arrayTypeKeyList.contains(targetKey)){
		  			param.put(targetKey, "Array");
		  			param.put(targetKey+"[]", req.getParameter(targetKey));
		  		}else
		  			param.put(targetKey, req.getParameter(targetKey));
		  		
		  		
		  		cacheUrl = uriRoot + "./?m=pc&a=" + targetId_to_cacheAction.get(targetKey)
		  					+ "&" + targetId_to_parentId.get(targetKey) + "=" +  parentParam.get(targetId_to_parentId.get(targetKey));
		  		break;
	  		}
  		}
	  	log.info("param = " + param.toString());
		try {
			HttpMethod.doPost(uriRoot, param);

			if(cacheUrl.length() > 0)
				cacheManager.updateImmediate(cacheUrl, AgriCacheManager.assignConverter(cacheUrl));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	  throws ServletException, IOException {
	
		Authentication auth = (Authentication)req.getSession().getAttribute("auth");
		
		if("delete_topic".equals(req.getParameter("a")) ||
			"delete_comment".equals(req.getParameter("a"))){
			processTopic(req, auth);
			return;
		}

		String imageFileNameBase = "image_filename";
		Map<String, String> param = new LinkedHashMap<String, String>();
	  	param.put("m", "pc");

	  	Map<String, String> targetId_to_ActionMap = new HashMap<String, String>();
	  		targetId_to_ActionMap.put("target_c_commu_id", "page_c_topic_add_confirm");
	  		targetId_to_ActionMap.put("target_c_commu_topic_id", "page_c_topic_write_confirm");
	  		targetId_to_ActionMap.put("target_c_diary_id", "page_fh_diary_comment_confirm");
	  		targetId_to_ActionMap.put("page_fh_diary_list", "page_h_diary_add_confirm");
	  		targetId_to_ActionMap.put("target_c_album_id", "page_h_album_image_add_confirm");
	  		targetId_to_ActionMap.put("target_c_member_id", "page_f_message_send_confirm");
		Map<String, String> targetId_to_cacheAction = new HashMap<String, String>();
			targetId_to_cacheAction.put("target_c_commu_id", "page_c_topic_list");
			targetId_to_cacheAction.put("target_c_commu_topic_id", "page_c_topic_detail");
			targetId_to_cacheAction.put("target_c_diary_id", "page_fh_diary");
			targetId_to_cacheAction.put("target_c_album_id", "page_fh_album");
			targetId_to_cacheAction.put("target_c_member_id", "page_h_message_box&box=outbox");

		String topicUrl = req.getParameter("topicId");
		String cacheUrl = "";
		String topicId = "1";
		log.info("topicUrl = " + topicUrl);
		Matcher mat = null;
	  	if(topicUrl != null){
	  		for(String targetKey : targetId_to_ActionMap.keySet()){
		  		if(topicUrl.indexOf(targetKey) != -1){

			  		param.put("a", targetId_to_ActionMap.get(targetKey));

			  		mat = Pattern.compile("&" + targetKey + "=([0-9]*)").matcher(topicUrl);
			  		if(mat.find()){
			  			topicId = mat.group(1);
			  			param.put(targetKey, topicId);
				  		cacheUrl = uriRoot + "./?m=pc&a=" + targetId_to_cacheAction.get(targetKey);
				  		if (!targetKey.equals("target_c_member_id"))
				  			cacheUrl += "&" + targetKey + "=" + topicId;

				  		if (targetKey.equals("target_c_diary_id")
				  		 || targetKey.equals("target_c_album_id")
				  		 || targetKey.equals("target_c_member_id"))
				  				imageFileNameBase = "upfile_";

			  		} else if (targetKey.equals("page_fh_diary_list")) {
			  			topicId = "N/A";
			  			cacheUrl = uriRoot + "./?m=pc&a=page_fh_diary_list";
			  			imageFileNameBase = "upfile_";
			  		}

			  		break;
		  		}
	  		}
	  	}
	  	log.info("topicId = " + topicId);

	  	param.put("MAX_FILE_SIZE", "15728640");
	  	param.put("body", req.getParameter("body"));
	  	Map<String, BlobKey> blobs = blobStoreService.getUploadedBlobs(req);
	  	
	  	String title = req.getParameter("title");
	  	if(title != null && title.length() > 40)
	  		title = title.substring(0, 40);

	  	if(topicUrl.indexOf("target_c_commu_id") != -1){
	  		param.put("title", title);
	  	} else if (topicUrl.indexOf("target_c_member_id") != -1) {
	  		param.put("subject", title);
	  		param.put("target_c_message_id", "");
	  		param.put("jyusin_c_message_id", "");
	  		param.put("box", "");
	  	} else if (topicUrl.indexOf("page_fh_album") != -1) {

	  		param.remove("body");
	  		param.put("subject", title);

	  		for(int i = 1; i<=blobs.keySet().size(); i++)
	  			param.put("image_description"+i, req.getParameter("body"));

	  		//for(int i = blobs.keySet().size()+1; i<=5; i++)
	  			//param.put("upfile_"+i, "");

	  	} else if (topicUrl.indexOf("page_fh_diary_list") != -1) {
	  		param.put("subject", title);
	  		param.put("public_flag", req.getParameter("public_flag"));
	  		param.put("category", req.getParameter("category"));
	  	}

	  	param.put("sessid", auth.getSessid());
	  	
	  	log.info("param = " + param.toString());
	  	List<URL> fileList = new ArrayList<URL>();
	  	BlobKey blobKey = null;
	  	List<BlobKey> blobKeys = new ArrayList<BlobKey>();
	  	String blobImagePath = null;

	  	for(String keyStr : blobs.keySet()){
		  try{
			  blobKey = blobs.get(keyStr);
			  log.info("blobKey:" + keyStr);

			  blobImagePath = ImagesServiceFactory.getImagesService().getServingUrl(blobKey);
			  if(!blobImagePath.startsWith("http"))
			  		blobImagePath = selfRoot + blobImagePath;
				blobImagePath = blobImagePath.replace("//_ah", "/_ah");
				log.info("received to BlobStore:" + blobImagePath);

			  fileList.add(new URL(blobImagePath));
			  blobKeys.add(blobKey);
			  
		  }catch(Exception ex){
			  ex.printStackTrace();
		  }
	  }

	  String res = HttpMethod.doMultipartPost(
			  getServletContext().getInitParameter("UriRoot"),
			  param, fileList, imageFileNameBase);

	  log.info("MultipartPost res = \n" + res);
	  
	  for(BlobKey key : blobKeys)
		  blobStoreService.delete(key);

	  mat = Pattern.compile("<input type=\\\"hidden\\\" name=\\\"([^\\\"]*)\\\" value=\\\"([^\\\"]*)\\\"").matcher(res);
	  param.clear();
	  boolean hasParamM = false;
	  while(mat.find()){
		  if(mat.group(1).equals("m"))
			  if(!hasParamM)
				  hasParamM = true;
			  else
				  break;
		 
		  param.put(mat.group(1), mat.group(2));
	  }
	  HttpMethod.doPost(uriRoot, param);

	  if(cacheUrl.length() > 0)
		  cacheManager.updateImmediate(cacheUrl, AgriCacheManager.assignConverter(cacheUrl));
		  //cacheManager.scheduleUpdate(cacheUrl);

	  
	  resp.sendRedirect("/post.jsp");
	}
}
